package com.phiture.erp.produce.web.controller.admin;

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import com.phiture.erp.common.enums.ErpProductionTaskStatusEnum;
import com.phiture.erp.produce.core.pojo.dto.ErpProductionTaskPageReqDTO;
import com.phiture.erp.produce.core.pojo.dto.ErpProductionTaskReportDTO;
import com.phiture.erp.produce.core.pojo.dto.ErpProductionTaskSaveReqDTO;
import com.phiture.erp.produce.core.pojo.vo.ErpProductionTaskMaterialVO;
import com.phiture.erp.produce.core.pojo.vo.ErpProductionTaskProcessesVO;
import com.phiture.erp.produce.core.service.ErpProduceMainPlanService;
import com.phiture.erp.produce.core.service.ErpProductionTaskService;
import com.phiture.erp.produce.dal.entity.ErpProductionTaskDO;
import com.phiture.erp.produce.dal.pojo.vo.ErpProductionTaskRespVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.EXPORT;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

@Tag(name = "管理后台 - 生产任务")
@RestController
@RequiredArgsConstructor
@RequestMapping("/erp/production-task")
public class ErpProductionTaskController {
    private final ErpProductionTaskService productionTaskService;

    private final ErpProduceMainPlanService produceMainPlanService;

    @PostMapping("/create")
    @Operation(summary = "创建生产任务")
    @PreAuthorize("@ss.hasPermission('erp:production-task:create')")
    public CommonResult<Long> createProductionTask(@Valid @RequestBody ErpProductionTaskSaveReqDTO createReqDTO) {
        return success(productionTaskService.createProductionTask(createReqDTO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新生产任务")
    @PreAuthorize("@ss.hasPermission('erp:production-task:update')")
    public CommonResult<Boolean> updateProductionTask(@Valid @RequestBody ErpProductionTaskSaveReqDTO updateReqDTO) {
        productionTaskService.updateProductionTask(updateReqDTO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除生产任务")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('erp:production-task:delete')")
    public CommonResult<Boolean> deleteProductionTask(@RequestParam("id") Long id) {
        productionTaskService.deleteProductionTask(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得生产任务")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('erp:production-task:query')")
    public CommonResult<ErpProductionTaskRespVO> getProductionTask(@RequestParam("id") Long id) {
        ErpProductionTaskDO productionTask = productionTaskService.getProductionTask(id);
        return success(BeanUtils.toBean(productionTask, ErpProductionTaskRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得生产任务分页")
    @PreAuthorize("@ss.hasPermission('erp:production-task:query')")
    public CommonResult<PageResult<ErpProductionTaskRespVO>> getProductionTaskPage(@Valid ErpProductionTaskPageReqDTO pageReqDTO) {
        PageResult<ErpProductionTaskRespVO> pageResult = productionTaskService.getProductionTaskPage(pageReqDTO);
        pageResult.getList().forEach(task -> {
            task.setStatusName( ErpProductionTaskStatusEnum.getStatusName(task.getStatus()));
        });
        return success(pageResult);
    }


    @GetMapping("/pageMobile")
    @Operation(summary = "获得生产任务分页")
    @PreAuthorize("@ss.hasPermission('erp:production-task:query')")
    public CommonResult<PageResult<ErpProductionTaskRespVO>> getProductionTaskPageMobile(@Valid ErpProductionTaskPageReqDTO pageReqDTO) {
        PageResult<ErpProductionTaskRespVO> pageResult = productionTaskService.getProductionTaskPageForMobile(pageReqDTO);
        pageResult.getList().forEach(task -> {
            task.setStatusName( ErpProductionTaskStatusEnum.getStatusName(task.getStatus()));
        });
        return success(pageResult);
    }

    private PageResult<ErpProductionTaskRespVO> buildPageResult(PageResult<ErpProductionTaskRespVO> pageResult) {
        // 如果没有数据，直接返回
        if (pageResult.getList().isEmpty()) {
            return BeanUtils.toBean(pageResult, ErpProductionTaskRespVO.class);
        }
//        // 获取所有生产任务的主计划单号
//        List<String> mainPlanNos = pageResult.getList().stream().map(ErpProductionTaskDO::getProductMainPlanNo).collect(Collectors.toList());
//        // 查出所有主计划单号的销售订单号
//        Map<String, String> mainPlanNoSaleOrderNoMap = produceMainPlanService.getMainPlanNoSaleOrderNoMapByMainPlanNos(mainPlanNos);

        PageResult<ErpProductionTaskRespVO> result = BeanUtils.toBean(pageResult, ErpProductionTaskRespVO.class);
        // 设置销售订单号
        result.getList().forEach(task -> {
//            task.setSaleOrderNo(mainPlanNoSaleOrderNoMap.get(task.getProductMainPlanNo()));
            task.setStatusName( ErpProductionTaskStatusEnum.getStatusName(task.getStatus()));
        });
        return result;
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出生产任务 Excel")
    @PreAuthorize("@ss.hasPermission('erp:production-task:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportProductionTaskExcel(@Valid ErpProductionTaskPageReqDTO pageReqDTO,
              HttpServletResponse response) throws IOException {
        pageReqDTO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<ErpProductionTaskRespVO> list = productionTaskService.getProductionTaskPage(pageReqDTO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "生产任务.xls", "数据", ErpProductionTaskRespVO.class,
                        BeanUtils.toBean(list, ErpProductionTaskRespVO.class));
    }

    @PostMapping("/report-work")
    @Operation(summary = "报工")
    @PreAuthorize("@ss.hasPermission('erp:production-task:report')")
    public CommonResult<Boolean> reportWork(@Valid @RequestBody ErpProductionTaskReportDTO reportDTO) {
        productionTaskService.reportWork(reportDTO);
        return success(true);
    }

    // ==================== 子表（生产任务单物料清单） ====================

    @GetMapping("/production-task-material/list-by-production-task-id")
    @Operation(summary = "获得生产任务单物料清单列表")
    @Parameter(name = "productionTaskId", description = "任务单ID")
    @PreAuthorize("@ss.hasPermission('erp:production-task:query')")
    public CommonResult<List<ErpProductionTaskMaterialVO>> getProductionTaskMaterialListByProductionTaskId(@RequestParam("productionTaskId") Long productionTaskId,
                                                                                                           @RequestParam(value = "processId", required = false) Long processId) {
        return success(productionTaskService.getProductionTaskMaterialListByProductionTaskId(productionTaskId, processId));
    }

    // ==================== 子表（生产任务单工序） ====================

    @GetMapping("/production-task-processes/list-by-production-task-id")
    @Operation(summary = "获得生产任务单工序列表")
    @Parameter(name = "productionTaskId", description = "任务单ID")
    @PreAuthorize("@ss.hasPermission('erp:production-task:query')")
    public CommonResult<List<ErpProductionTaskProcessesVO>> getProductionTaskProcessesListByProductionTaskId(@RequestParam("productionTaskId") Long productionTaskId) {
        return success(productionTaskService.getProductionTaskProcessesListByProductionTaskId(productionTaskId));
    }



}